var http = require('http');
var formidable = require('formidable');
var qs = require('querystring');
var util = require('util');
var path = require('path');
var fs = require('fs');

var root = process.cwd();

http.createServer(function(req,res){
  if (req.url == '/') {
    switch (req.method){
      case 'GET':
        show(res);
        break;
      case 'POST':
        upload(req,res);
        break;
      default:
        badReq(res);
    }
  }else{
    notFound(res);
  }
}).listen(9000);

console.log('Server is started @9000');

function show(res){
  var pageContent1 = '<html><head><title>Upload</title></head><body>'
    + '<h1>Upload Files</h1>'
    + '<form method="POST" action="/" enctype="multipart/form-data">'
    + '<p><input type="text" name="name"></p>'
    + '<p><input type="file" name="file"></p>'
    + '<p><input type="submit" value="upload"></p>'
    + '</form>';
  res.setHeader('Content-Type','text/html');
  res.setHeader('Content-length', Buffer.byteLength(pageContent1));
  res.end(pageContent1);
}

function upload(req,res){
  var type = req.headers['Content-Type'] || '';
  if(type.indexOf("multipart/form-data")){
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload:\n\n');
      var name = fields.name;
      var filename = files.file.name;
      console.log(name + '+' +filename);
      fs.rename(files.file.path,path.join(root,filename),function(err){
        if(err){
          res.end('Upload Error');
        }else{
          res.end('Upload Success');
        }
      });
    });
  }else{
    res.statusCode = 400;
    res.end('Bad Request!');
  }
}

function badReq(res){
  res.statusCode = 500;
  res.end('Internal error');
}

function notFound(res){
  res.statusCode = 404;
  res.end('Not Found');
}
